import requests,os
import time
import json

myhost = "http://oss.breaker.club/feimao"

url = "https://肥猫.live"
# url = "http://饭太硬.top/tv"

# 获取今天的年月日
dirName = input("输入存储路径:")
if len(dirName) == 0:
	dirName = time.strftime("%Y%m%d", time.localtime())
	
# 判断文件夹是否存在
if os.path.exists(dirName):
	print("文件夹已存在")
else:
	os.makedirs(dirName)


def saveMainJson(data):
	# save sites
	data["spider"] = "http://oss.breaker.club/feimao/jar/PandaQ231205.jar;md5;9cc29f6286b2fe7910628852929c4bdb"
	nSites = []
	sites = data['sites']
	keys = ["api", "ext", "jar"]
	suffixs = ["js", "json", "jar"]
	for site in sites:
		for key in keys:
			if key in site:
				url = site[key]
				if isinstance(url, str) == False:
					continue
				if url.startswith("http") == False:
					continue

				fileName = url.split("/")[-1]
				suffix = fileName.split(".")[-1]
				suffix = suffix.lower()
				if suffix not in suffixs:
					continue

				savePath = "{}/{}/{}".format(dirName,suffix,fileName)
				site[key] = "{}/{}/{}".format(myhost,suffix,fileName)
				if os.path.exists(savePath) == True:
					continue
				
				os.system("wget -P {}/{}/ {}".format(dirName,suffix,url))
		
		nSites.append(site)

	data["sites"] = nSites
	f = open("{}/index.json".format(dirName), "w")
	f.write(json.dumps(data))
	f.close()

def saveMainJar(data):
	spiderUrl = data['spider']
	os.system("wget -P {}/jar {}".format(dirName,spiderUrl))

def saveOtherFile(data):
	sites = data['sites']
	for site in sites:
		if "api" in site:
			saveJsIFNeed(site['api'])
			saveJarIFNeed(site['api'])
			saveJsonIFNeed(site['api'])

		if "ext" in site:
			if isinstance(site['ext'], str) == False:
				continue
			saveJsIFNeed(site['ext'])
			saveJarIFNeed(site['ext'])
			saveJsonIFNeed(site['ext'])


def saveJsIFNeed(api):
	if api.startswith("http") and api.endswith(".js"):
		fileName = api.split("/")[-1]
		savePath = "{}/js/{}".format(dirName,fileName)
		if os.path.exists(savePath) == False:
			os.system("wget -P {}/js/ {}".format(dirName,api))

def saveJarIFNeed(api):
	if api.startswith("http") and api.endswith(".jar"):
		fileName = api.split("/")[-1]
		savePath = "{}/jar/{}".format(dirName,fileName)
		if os.path.exists(savePath) == False:
			os.system("wget -P {}/jar/ {}".format(dirName,api))

def saveJsonIFNeed(api):
	if api.startswith("http") and api.endswith(".json"):
		fileName = api.split("/")[-1]
		savePath = "{}/json/{}".format(dirName,fileName)
		if os.path.exists(savePath) == False:
			os.system("wget -P {}/json/ {}".format(dirName,api))

if __name__ == '__main__':
	res = requests.get(url, headers={"user-agent":"okhttp"})
	res.encoding = "utf-8"
	print(res.status_code)

	f = open("{}/ori.json".format(dirName), "w")
	f.write(res.text)
	f.close()

	if res.status_code == 200 and len(res.text) > 0:
		print("下载成功")
		saveMainJson(res.json())
		# saveMainJar(res.json())
		# saveOtherFile(res.json())